package com.ruoyi.system.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.stu.mapper.StuStudentUnitMapper;
import com.ruoyi.stu.mapper.StuStudentWordMapper;
import com.ruoyi.system.domain.SysCourse;
import com.ruoyi.system.domain.SysStudent;
import com.ruoyi.system.domain.SysStudentCourse;
import com.ruoyi.system.domain.SysTextbook;
import com.ruoyi.system.domain.SysUnit;
import com.ruoyi.system.mapper.SysCourseMapper;
import com.ruoyi.system.mapper.SysStudentCourseMapper;
import com.ruoyi.system.mapper.SysStudentMapper;
import com.ruoyi.system.mapper.SysTextbookMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysStudentService;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysStudentServiceImpl implements ISysStudentService
{
    private static final Logger log = LoggerFactory.getLogger(SysStudentServiceImpl.class);

    @Autowired
    private StuStudentUnitMapper stuStudentUnitMapper;
    @Autowired
    private StuStudentWordMapper stuStudentWordMapper;
    @Autowired
    private SysStudentMapper sysStudentMapper;
    @Autowired
    private SysStudentCourseMapper sysStudentCourseMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysTextbookMapper sysTextbookMapper;
    @Autowired
    private SysCourseMapper sysCourseMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    /**
     * 根据条件分页查询用户列表
     * 
     * @param entity 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysStudent> list(SysStudent entity, Integer pageNum, Integer pageSize)
    {
    	String orderby = "u.student_id desc";
    	
    	pageSize = pageSize != null ? pageSize : 10;
    	pageNum = pageNum != null ? pageNum - 1 : 0;
    	Integer start = pageNum * pageSize;
    	System.out.println("size---" + pageSize);
        return sysStudentMapper.list(entity, start, pageSize, orderby);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysStudent> selectAllocatedList(SysStudent user)
    {
        return sysStudentMapper.listAllocated(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysStudent> selectUnallocatedList(SysStudent user)
    {
        return sysStudentMapper.listUnallocated(user);
    }

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysStudent selectStudentByName(String userName)
    {
        return sysStudentMapper.selectByName(userName);
    }

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysStudent selectById(Long userId)
    {
        return sysStudentMapper.selectById(userId);
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysStudent student)
    {
        Long studentId = StringUtils.isNull(student.getStudentId()) ? -1L : student.getStudentId();
        SysStudent info = sysStudentMapper.checkUserNameUnique(student.getStudentName());
        if (StringUtils.isNotNull(info) && info.getStudentId().longValue() != studentId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param entity 学生信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysStudent entity)
    {
        Long studentId = StringUtils.isNull(entity.getStudentId()) ? -1L : entity.getStudentId();
        SysStudent info = sysStudentMapper.checkPhoneUnique(entity.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getStudentId().longValue() != studentId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存用户信息
     * 
     * @param entity 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insert(SysStudent entity)
    {
    	// 验证有效期
    	if (entity.getExpireTime() == null || entity.getExpireTime().length() == 0) {
			return 0;
		}
    	entity.setExpireTime(entity.getExpireTime().substring(0, 10));
    	
        // 设置默认昵称
        if (StringUtils.isEmpty(entity.getRealName()))
        {
            entity.setRealName(entity.getRealName());
        }
        // 设置每组默认学习单词数为10
    	entity.setWordsPerGroup(entity.getWordsPerGroup() == null ? 10 : entity.getWordsPerGroup());
        // 设置默认复习单词数为50
		entity.setMaxReviewWords(entity.getMaxReviewWords() == null ? 50 : entity.getMaxReviewWords());
        // 设置默认听写时长(秒)
		entity.setDictationDuration(entity.getDictationDuration() == null ? 30 : entity.getDictationDuration());
		// 设置默认背景音乐开启
		entity.setAlphaMusic(entity.getAlphaMusic() == null ? 0 : entity.getAlphaMusic());
        // 新增用户信息
        int rows = sysStudentMapper.insert(entity);
        
        // 往用户表也添加一条数据，关联学生ID
        SysUser sysUser = new SysUser();
        sysUser.setAvatar(entity.getAvatar());
        sysUser.setUserName(entity.getStudentName());
        sysUser.setRealName(entity.getRealName());
        sysUser.setNickName(entity.getStudentName());
        sysUser.setPhonenumber(entity.getPhonenumber());
        sysUser.setPassword(entity.getPassword());
        sysUser.setStatus(entity.getStatus());
        sysUser.setStudentId(entity.getStudentId());
        sysUser.setTeacherId(0L);
        sysUser.setDelFlag("1");
        sysUserMapper.insertUser(sysUser);
        return rows;
    }

    /**
     * 注册用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerStudent(SysStudent user)
    {
        // 设置默认昵称
        if (StringUtils.isEmpty(user.getRealName()))
        {
            user.setRealName(user.getStudentName());
        }
        return sysStudentMapper.insert(user) > 0;
    }

    /**
     * 修改保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int update(SysStudent student)
    {
        SysUser sysUser = sysUserMapper.selectUserByStudentId(student.getStudentId());
        
        // 密码加密
        if (student.getPassword() != null && student.getPassword().length() > 0) {
            student.setPassword(SecurityUtils.encryptPassword(student.getPassword()));
            sysUser.setPassword(student.getPassword());
		}
        // 有效期格式
        if (student.getExpireTime() != null && student.getExpireTime().length() > 10) {
        	
    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            df.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date parse = null;
			try {
				parse = df.parse(student.getExpireTime());
			} catch (ParseException e) {
				e.printStackTrace();
			}
            SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
            
        	student.setExpireTime(df2.format(parse));
		}
        
    	sysStudentMapper.update(student);
    	
    	sysUser.setUserName(student.getStudentName());
    	sysUser.setPhonenumber(student.getPhonenumber());
    	sysUser.setStatus(student.getStatus());
        
        sysUserMapper.updateUser(sysUser);
        return 1;
    }

    /**
     * 修改用户状态
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateStatus(SysStudent user)
    {
        return sysStudentMapper.update(user);
    }

    /**
     * 修改用户基本信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateProfile(SysStudent user)
    {
        return sysStudentMapper.update(user);
    }

    /**
     * 修改用户头像
     * 
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateAvatar(String userName, String avatar)
    {
    	int num = sysStudentMapper.updateAvatar(userName, avatar);
    	// 同时同步用户头像
    	sysUserMapper.updateUserAvatar(userName, avatar);
        return num > 0;
    }

    /**
     * 重置用户密码
     * 
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetPwd(String userName, String password)
    {
        return sysStudentMapper.resetPwd(userName, password);
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteById(Long userId)
    {
        return sysStudentMapper.deleteById(userId);
    }

    /**
     * 批量删除用户信息
     * 
     * @param studentIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteByIds(Long[] studentIds)
    {
        return sysStudentMapper.deleteByIds(studentIds);
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysStudent> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysStudent user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysStudent u = sysStudentMapper.selectByName(user.getStudentName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    sysStudentMapper.insert(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getStudentName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setStudentId(u.getStudentId());
                    user.setUpdateBy(operName);
                    sysStudentMapper.update(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getStudentName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getStudentName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getStudentName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询已分配班级的学员列表
     * 
     * @param classId 班级ID
     * @return 用户列表
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysStudent> selectAssignedList(Long classId)
    {
        return sysStudentMapper.selectAssignedList(classId);
    }

    /**
     * 查询未分配班级的学员列表
     * 
     * @param classId 班级ID
     * @return 用户列表
     */
    @Override
    public List<SysStudent> listAll()
    {
        return sysStudentMapper.listAll();
    }

    /**
     */
    @Override
    public List<TreeSelect> courseTree(SysCourse sysCourse)
    {
        
        // 添加顶级【全部教材】
        List<TreeSelect> listRoot = new ArrayList<TreeSelect>();
        {
        	Long id = 0L;
        	String label = "全部教材";
        	boolean disabled = false;
        	Integer lev = 0;
        	List<TreeSelect> children = getTextbookTree();
            listRoot.add(new TreeSelect(id, label, disabled, lev, children));
        }
        return listRoot;
    }
    
    public List<TreeSelect> getTextbookTree()
    {
        List<SysTextbook> listSysTextbook = sysTextbookMapper.selectList(new SysTextbook());
        List<SysCourse> listSysCourse = sysCourseMapper.list(new SysCourse());
        
        // 添加教材节点列表
        List<TreeSelect> listTextbookTree = new ArrayList<TreeSelect>();
        for(SysTextbook sysTextbook : listSysTextbook) {
        	Long id = sysTextbook.getTextbookId();
        	String label = sysTextbook.getTextbookName();
        	boolean disabled = false;
        	Integer lev = 1;
        	List<TreeSelect> children = getCourseTree(sysTextbook, listSysCourse);
        	if (children == null || children.size() == 0) {
				continue;
			}
        	listTextbookTree.add(new TreeSelect(id, label, disabled, lev, children));
        }
        return listTextbookTree;
    }
    
    public List<TreeSelect> getCourseTree(SysTextbook sysTextBook, List<SysCourse> listSysCourse)
    {
        
        // 添加教材节点列表
        List<TreeSelect> listCourseTree = new ArrayList<TreeSelect>();
        for(SysCourse sysCourse : listSysCourse) {
        	if (sysCourse.getTextbookId().longValue() != sysTextBook.getTextbookId().longValue()) {
				continue;
			} else {
	        	Long id = sysCourse.getCourseId();
	        	String label = sysCourse.getCourseName();
	        	boolean disabled = false;
	        	Integer lev = 2;
	        	List<TreeSelect> children = null;
	        	listCourseTree.add(new TreeSelect(id, label, disabled, lev, children));
			}
        }
        return listCourseTree;
    }

    /**
     * 批量添加学员-课程
     * @return 结果
     */
    @Override
    @Transactional
    public void insertStudentCourse(Long studentId, Long[] courseIds)
    {
        // 新增班级与学员关联
        List<SysStudentCourse> list = new ArrayList<SysStudentCourse>();
        for (Long courseId : courseIds) {
        	
        	SysStudentCourse e = new SysStudentCourse();
            e.setStudentId(studentId);
            e.setCourseId(courseId);
            list.add(e);
        }
        
        // 删除学员的所有课程
        sysStudentCourseMapper.deleteByStudentId(studentId);
        // 添加学员-课程
        sysStudentCourseMapper.insertBatch(list);
        // 删除不在学员课程内的学员-单元
        stuStudentUnitMapper.deleteNotInCourse(studentId);
        // 添加学员-单元，若已经存在，则不添加
        for (Long courseId : courseIds) {
        	SysUnit entity = new SysUnit();
        	entity.setCourseId(courseId);
        	Integer num = stuStudentUnitMapper.countByStudentIdAndCourseId(studentId, courseId);
        	if (num == 0) {
        		stuStudentUnitMapper.insertBatchByCourseId(studentId, courseId);
			}
        }
        // 删除不在学员-课程内的学员-单词
        stuStudentWordMapper.deleteNotInCourse(studentId);
        // 按照课程批量添加学员-单词
        for (Long courseId : courseIds) {
        	SysUnit entity = new SysUnit();
        	entity.setCourseId(courseId);
        	Integer num = stuStudentWordMapper.countByStudentIdAndCourseId(studentId, courseId);
        	if (num == 0) {
        		stuStudentWordMapper.insertBatchByCourseId(studentId, courseId);
			}
        }
        
    }
}
